import { AIConfig } from './types';
import { configUI } from './ConfigUI';

// 配置管理器
export class ConfigManager {
  private static instance: ConfigManager;
  private config: Partial<AIConfig> = {};

  private constructor() {
    this.loadFromEnvironment();
    this.loadFromCookie();
  }

  static getInstance(): ConfigManager {
    if (!ConfigManager.instance) {
      ConfigManager.instance = new ConfigManager();
    }
    return ConfigManager.instance;
  }

  // 从环境变量加载配置
  private loadFromEnvironment(): void {
    // 在浏览器环境中，我们需要通过其他方式获取配置
    // 这里先设置默认值，实际使用时需要通过配置文件或用户输入
    this.config = {
      apiUrl: 'https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation',
      model: 'qwen-max',
      maxTokens: 1000,
      temperature: 0.7,
      timeout: 30000
    };
  }

  // 从Cookie加载配置
  private loadFromCookie(): void {
    try {
      const fullConfig = configUI.getFullConfig();
      if (fullConfig) {
        this.config = { ...this.config, ...fullConfig };
      }
    } catch (error) {
      console.warn('Failed to load config from cookie:', error);
    }
  }

  // 保存配置到Cookie
  private saveToCookie(): void {
    // ConfigUI会处理cookie的保存
  }

  // 获取配置
  getConfig(): Partial<AIConfig> {
    return { ...this.config };
  }

  // 更新配置
  updateConfig(newConfig: Partial<AIConfig>): void {
    this.config = { ...this.config, ...newConfig };
    this.saveToCookie();
  }

  // 设置API密钥
  setApiKey(apiKey: string): void {
    this.config.apiKey = apiKey;
  }

  // 从ConfigUI重新加载配置
  reloadConfig(): void {
    this.loadFromCookie();
  }

  // 获取完整的AI配置
  getAIConfig(): AIConfig | null {
    if (!this.isConfigComplete()) {
      return null;
    }

    return {
      apiUrl: this.config.apiUrl!,
      apiKey: this.config.apiKey!,
      model: this.config.model!,
      maxTokens: this.config.maxTokens!,
      temperature: this.config.temperature!,
      timeout: this.config.timeout!
    };
  }

  // 检查配置是否完整
  isConfigComplete(): boolean {
    return !!(
      this.config.apiUrl &&
      this.config.apiKey &&
      this.config.model &&
      this.config.maxTokens &&
      this.config.temperature !== undefined &&
      this.config.timeout
    );
  }

  // 重置配置
  resetConfig(): void {
    this.config = {};
    configUI.clearConfig();
    this.loadFromEnvironment();
  }

  // 验证API密钥格式
  validateApiKey(apiKey: string): boolean {
    // 千问API密钥通常以sk-开头
    return apiKey.length > 10 && /^[a-zA-Z0-9\-_]+$/.test(apiKey);
  }

  // 获取配置状态信息
  getConfigStatus(): {
    isComplete: boolean;
    missingFields: string[];
    hasApiKey: boolean;
  } {
    const requiredFields = ['apiUrl', 'apiKey', 'model', 'maxTokens', 'temperature', 'timeout'];
    const missingFields = requiredFields.filter(field => !this.config[field as keyof AIConfig]);

    return {
      isComplete: this.isConfigComplete(),
      missingFields,
      hasApiKey: !!this.config.apiKey
    };
  }
}

// 导出单例实例
export const configManager = ConfigManager.getInstance();